package org.dfzt.common.util;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class XssFilterUtil {
    private static final String replacedString="INVALID";
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    /**
     * 使用自带的basicWithImages 白名单
     * 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span,
     * strike,strong,sub,sup,u,ul,img
     * 以及a标签的href,img标签的src,align,alt,height,width,title属性
     */
    private static final Whitelist whitelist = Whitelist.basicWithImages();

    /** 配置过滤化参数,不对代码进行格式化 */
    private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
    static {
        // 富文本编辑时一些样式是使用style来进行实现的
        // 比如红色字体 style="color:red;"
        // 所以需要给所有标签添加style属性
        whitelist.addAttributes(":all", "style");

        String sqlKey = "and|exec|insert|drop|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
        String[] keyStr = sqlKey.split("\\|");
        notAllowedKeyWords.addAll(Arrays.asList(keyStr));
    }

    public static String clean(String content) {
        if(content==null||content.trim().length()==0||"null".equalsIgnoreCase(content)){
            return null;
        }
        cleanSqlKeyWords(content);
        return Jsoup.clean(content, "", whitelist, outputSettings);
    }

    private static void cleanSqlKeyWords(String paramValue) {
        for (String keyword : notAllowedKeyWords) {
            if (paramValue.length() > keyword.length() + 4
                    && (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) {
                paramValue = StringUtils.replace(paramValue, keyword, replacedString);
            }
        }
    }
}
